from PySide6.QtCore import Signal, QObject
from coapthon.client.helperclient import HelperClient

class CoapClient(QObject):
    CoapFinished = Signal(bool, str, str, str)
    CoapFailed = Signal(str)

    def __init__(self):
        super().__init__()

        self.__timeout = 2000
        self.__IP = ""

    def __del__(self):
        if (self.__QCoapClient is not None):
            self.__QCoapClient.stop()
            self.__QCoapClient.close()
            del self.__QCoapClient
            self.__QCoapClient = None

    def SetIP(self, ip):
        if ip != self.__IP:
            self.__IP = ip
            self.__QCoapClient = HelperClient(server=(ip, 5683))

    def Post(self, url, content):
        self.__url = url
        self.__content = content
        self.__QCoapClient.post(url, content, self.on_Finished, self.__timeout)

    def SetTimeout(self, timeout):
        self.__timeout = timeout * 1000

    def on_Finished(self, response):
        if not response is None:
            print("Reply finished:" + response.payload)
            self.CoapFinished.emit(True, "coap://" + self.__IP + self.__url, self.__content, response.payload)
        else:
            self.CoapFinished.emit(False, None, None, None)


